"""
Copyright (c) 2023 - present SKbioinfo
"""
from apps.API.electricSigature.AuditRecord import Part11AuditRecord as Arc
from flask_restful import Resource, request
from flask import jsonify,current_app
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.sshExeCutor.util import executor_cmd
from flask_jwt_extended import jwt_required
from apps.API.pipeExecutor.models import Analysis
import pandas as pd
import os
'''
    Sample infos
'''
class interfaceFecthResumeInfo(Resource):
    @jwt_required()
    def get(self):
        try:
            username=request.args.get('username')
            page=int(request.args.get('page'))
            limit=int(request.args.get('limit'))
            query=Analysis.query.order_by(Analysis.run_id.desc())
            if username not in ['admin']:
                query=query.filter(Analysis.username==username)
            query=query.filter(Analysis.run_status==-1)
            total_length=query.count()
            pagination=query.paginate(page=page, per_page=limit, error_out=False)
            results=[item.to_dict() for item in pagination.items]
            response=jsonify({"total":total_length,"data":results})
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            response=jsonify({})
            response.status=404
            return response
        
class interfaceResumeID(Resource):
    def __init__(self):
        self.executor=executor_cmd()
    '''
        POST: resume analysis
    '''
    @jwt_required()
    def post(self,run_id):
        try:
            for row in request.json["data"]:
                base_dir=current_app.config.get("BASE_DIR")
                dir_path=base_dir + "run"
                tag=row["type"]
                if tag in ["mNGS","tNGS"]:
                    run_file_path = os.path.join(dir_path,f'{tag}/{run_id}/run_newstandard.sh')
                    run_cmd=f'''sh {run_file_path}'''
                    self.executor.sshpass_cmd(run_cmd)
                    update_info_sql = f'''UPDATE analysis SET run_status=0 WHERE run_id=\"{run_id}\"'''
                    update_info(update_info_sql)
                    ### 记录重投 ###
                    Arc.add_aduit_record(
                        record_type="PIPELINE_RESUME",
                        content=f"Resume {tag} Pipeline With RUN_ID:{run_id}",
                        username=request.json["userName"]
                    )
                    return 202
                else:
                    return 300
        except Exception as e:
           lg.error(e)
           return 404